package com.study.juc.lk;

import java.util.concurrent.TimeUnit;

/**
 * @program: juc-study
 * @author: Zhoujian
 * @date: 2022-08-13 11:15
 * @version: 1.0
 * @description: 死锁案例
 *  线程A持有A锁尝试获得B锁，线程B持有B锁尝试活都A锁
 *  需要加sleep效果才能很快暴露
 **/
public class DeadLockDemo {
	public static void main(String[] args) {
		Object a = new Object();
		Object b = new Object();

		new Thread(() -> {
			synchronized (a){
				System.out.println(Thread.currentThread().getName() + "持有A锁，尝试获得B锁");
				try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
				synchronized (b){
					System.out.println(Thread.currentThread().getName() + "尝试获得B锁");
				}
			}
		},"a").start();
		new Thread(() -> {
			synchronized (b){
				System.out.println(Thread.currentThread().getName() + "持有B锁，尝试获得A锁");
				try {TimeUnit.SECONDS.sleep(1);	} catch (InterruptedException e) {e.printStackTrace();				}
				synchronized (a){
					System.out.println(Thread.currentThread().getName() + "尝试获得A锁");
				}
			}
		},"b").start();
	}
}
